<template>
  <div>
    <el-row>
      <el-col
          :span="4"
          v-for="(item, index) in categoryList"
          :key="index"
          align="middle"
          justify="center"
          class="category-item"
      >
        <div>{{item.name}}</div>
        <el-col>
          <img
              :src="baseUrl + item.image"
              alt=""
              width="120"
              style="border-radius: 100px;"
              class="category-image"
          >
        </el-col>
        <el-row justify="center" class="category-actions">
          <el-button type="primary" @click="openUpdateDialog(item)" size="small">修改</el-button>
          <el-button type="danger" @click="del(item.id)" size="small">删除</el-button>
        </el-row>
      </el-col>

      <el-col :span="4" align="middle" justify="center" class="add-category">
        <el-button type="primary" @click="addCategory" size="large" icon="plus">添加</el-button>
      </el-col>
    </el-row>

    <!-- 修改分类对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        append-to-body
        @closed="clearPreview"
    >
      <div style="margin-bottom: 20px">
        <label style="display: block; margin-bottom: 8px; font-weight: 500;">分类名称</label>
        <el-input
            v-model="editData.name"
            placeholder="请输入分类名称"
        />
      </div>

      <div style="margin-bottom: 20px">
        <label style="display: block; margin-bottom: 8px; font-weight: 500;">分类图片</label>
        <div v-if="editData.image" style="margin-bottom: 10px">
          <img
              :src="baseUrl + editData.image"
              alt="预览"
              style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px;"
          >
        </div>
        <el-upload
            action="http://192.168.90.26:8080/uploade/uploading"
            :auto-upload="true"
            :on-success="handleUploadSuccess"
        >
          <el-button type="primary">上传图片</el-button>
          <template #tip>
            <div style="font-size: 12px; color: #888; margin-top: 8px">
              支持JPG/PNG格式，文件小于2MB
            </div>
          </template>
        </el-upload>
      </div>

      <div style="text-align: right">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElDialog, ElInput, ElUpload, ElButton, ElMessage } from "element-plus";

const baseUrl = ref("http://192.168.90.26:8080/");
const categoryList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('修改分类');
const editData = ref({
  id: null,
  name: '',
  image: ''
});

onMounted(() => {
  fetchCategories();
});
const routeKey = ref(0)
const refreshProductList = () => {
  // 每次点击菜单时改变 key 值，触发组件刷新
  routeKey.value += 1
}
// 获取分类数据
const fetchCategories = () => {
  axios.get('category/findAll').then(res => {
    categoryList.value = res.data;
  });
};
// 打开修改对话框
const openUpdateDialog = (category) => {
  // 创建副本避免直接修改原数据
  editData.value = {
    id: category.id,
    name: category.name,
    image: category.image
  };
  dialogTitle.value = '修改分类';
  dialogVisible.value = true;
};

// 添加分类
const addCategory = () => {
  editData.value = {
    id: null,
    name: '',
    image: ''
  };
  dialogTitle.value = '添加分类';
  dialogVisible.value = true;
};

// 处理上传成功
const handleUploadSuccess = (res) => {
  // 假设返回的文件名在res.fileName
  if (res) {
    console.log('图片上传成功：', res)
    editData.value.image = res;
    ElMessage.success('图片上传成功');
  }
};

// 保存分类
const saveCategory = () => {
  if (!editData.value.name.trim()) {
    ElMessage.error('请输入分类名称');
    return;
  }

  if (editData.value.id) {
    // 更新操作
    axios.post('http://192.168.90.26:8080/category/update', editData.value).then(res => {
      if (res.data) {
        // 更新本地数据
        const index = categoryList.value.findIndex(c => c.id === editData.value.id);
        categoryList.value[index] = { ...editData.value };
        ElMessage.success('修改成功');
        dialogVisible.value = false;
      } else {
        ElMessage.error('修改失败');
      }
    });
  } else {
    // 添加操作
    axios.post('http://192.168.90.26:8080/category/add', editData.value).then(res => {
      if (res.data!=null) {
        // 添加新的分类
        const newCategory = {
          id: res.data, // 假设后端返回新创建的ID
          name: editData.value.name,
          image: editData.value.image
        };
        categoryList.value.push(newCategory);
        ElMessage.success('添加成功');
        dialogVisible.value = false;
      } else {
        ElMessage.error('添加失败');
      }
    });
  }
};
const clearPreview = () => {
  editData.value.image = '';
};
// 删除分类
const del = (id) => {
  if (!confirm('确定删除该分类吗？')) {
    return;
  }
  axios.get('http://192.168.90.26:8080/category/delete?id='+id,  ).then(res => {
    refreshProductList()
    if (res.data) {
      // 更新本地数据
      categoryList.value = categoryList.value.filter(item => item.id !== id);
      ElMessage.success('删除成功');
    } else {
      ElMessage.error('删除失败');
    }
  });
};
</script>

<style scoped>
.category-item {
  padding: 20px;
  margin: 10px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.category-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.category-image {
  margin: 10px 0;
  border: 1px solid #eee;
  padding: 5px;
}

.category-actions {
  margin-top: 15px;
}

.add-category {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  margin: 10px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.add-category:hover {
  background-color: #f5f7fa;
}
</style>